package top.dotgo.kit.oss;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.util.Date;

/**
 * @author：jornl
 * @date : 2019/3/4 23:19
 * @des:
 */
public class OssStsKit extends OssBaseKit {

    private static final String ROLE_SESSION_NAME = "xiaoxb-oss";
    private static final String STS_API_VERSION = "2015-04-01";
    private static final String POLICY = "{\n" +
            "  \"Version\": \"1\",\n" +
            "  \"Statement\": [\n" +
            "    {\n" +
            "      \"Effect\": \"Allow\",\n" +
            "      \"Action\": [\n" +
            "        \"oss:*\",\n" +
            "        \"oss:Get*\",\n" +
            "        \"oss:Put*\",\n" +
            "        \"oss:List*\"\n" +
            "      ],\n" +
            "      \"Resource\": [\n" +
            "        \"acs:oss:*:*:mini-shops/*\"\n" +
            "      ],\n" +
            "      \"Condition\": {}\n" +
            "    }\n" +
            "  ]\n" +
            "}";
    private static OssStsKit ossKit;

    private OssStsKit() {
    }

    public static OssStsKit get() {
        initClient();
        if (ossKit == null) {
            synchronized (OssPutKti.class) {
                if (ossKit == null) {
                    ossKit = new OssStsKit();
                }
            }
        }
        return ossKit;
    }

    /**
     * 获得访问令牌
     * <p>
     * securityToken;
     * accessKeySecret;
     * accessKeyId;
     * expiration;
     *
     * @return Credentials
     */
    public AssumeRoleResponse.Credentials getStsToken() {
        // 添加endpoint（直接使用STS endpoint，前两个参数留空，无需添加region ID）
        // 构造default profile（参数留空，无需添加region ID）
        IClientProfile profile = DefaultProfile.getProfile(REGION.replace("oss-", ""), ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        // 用profile构造client
        DefaultAcsClient client = new DefaultAcsClient(profile);
        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setVersion(STS_API_VERSION);
        request.setHttpContentType(FormatType.FORM);
        request.setRoleArn(ROLE_ARN);
        request.setRoleSessionName(ROLE_SESSION_NAME);
        request.setPolicy(POLICY);
        //有效期
        request.setDurationSeconds(DURATION_SECONDS * 60L);
        // 发起请求，并得到response

        try {
            final AssumeRoleResponse response = client.getAcsResponse(request);
            return response.getCredentials();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取某个oss文件的临时访问url
     *
     * @param ossPath ossPath
     * @param process process oss图片样式
     * @return String
     */
    public String getTempUrl(String ossPath, String process) {
        //设置有效期 默认 60分钟
        Date expiration = DateUtil.offsetMinute(DateUtil.date(), EXPIRATION);
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(BUCKET, ossPath);
        request.setExpiration(expiration);
        if (!StrUtil.isEmpty(process)) {
            request.setProcess(process);
        }
        return ossClient.generatePresignedUrl(request).toString();
    }

}
